package GUILayer;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Iterator;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

import CtrLayer.StaffCtr;
import ModelLayer.Staff;
import ModelLayer.StaffList;

public class StaffGUI {
	private JPanel panel;
	private JTable staffTable;
	private Object[][] data; // data for table
	private int size; // number of rows in table
	private static int idS = 1000;
	private static StaffCtr staffCtr = new StaffCtr();

	public StaffGUI() {

	}

	private JPanel makeGridListStaff() {
		Iterator<?> it = staffCtr.getStaffIterator();

		size = staffCtr.getStaffSize();

		String[] columnNames = { "Id", "Name", "Address", "Postal Code",
				"Phone", "email", "User Name", "Orders Sold" };
		data = new Object[size][columnNames.length];

		int i = 0;
		while (it.hasNext()) {
			Staff staff = (Staff) it.next();
			data[i][0] = staff.getId();
			data[i][1] = staff.getName();
			data[i][2] = staff.getAddress();
			data[i][3] = staff.getPostCode();
			data[i][4] = staff.getPhone();
			data[i][5] = staff.getEmail();
			data[i][6] = staff.getUsername();
			data[i][7] = staff.getOrdersSold();
			//data[i][8] = Boolean.FALSE;
			i++;
		}

		JPanel gridStaff = new JPanel();
		DefaultTableModel dtm = new DefaultTableModel(data, columnNames) {
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int row, int col) {
				return (col == 8);
			}

			public Class<?> getColumnClass(int col) {
				if (col == 8)
					return Boolean.class;
				return super.getColumnClass(col);
			}
		};

		staffTable = new JTable(dtm);
		staffTable.getTableHeader().addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				int col = staffTable.columnAtPoint(e.getPoint());
				if (col == 8) {
					int selected = getSelectedStaff(staffTable);
					if (selected == 0) {
						JOptionPane.showConfirmDialog(null,
								"You didn't select any employee", "Info",
								JOptionPane.CLOSED_OPTION);
					} else {
						int answer = JOptionPane.showConfirmDialog(null,
								"Are you sure you want to delete " + selected
										+ " employee(s) ?", "Confirm delete",
								JOptionPane.YES_NO_OPTION);
						if (answer == JOptionPane.YES_OPTION) {
							deleteSelectedStaff(staffTable);
						}
					}
				}
			}
	
		});

		TableColumnModel tcm = staffTable.getColumnModel();
		tcm.getColumn(0).setPreferredWidth(40);

		JScrollPane staffTableScroll = new JScrollPane(staffTable);
		staffTableScroll.setPreferredSize(new Dimension(600, 145));
		staffTableScroll
				.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		staffTableScroll
				.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

		gridStaff.add(staffTableScroll, BorderLayout.CENTER);

		staffTable.addMouseListener(new MouseAdapter() {

			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					JTable target = (JTable) e.getSource();
					int row = target.getSelectedRow();
					int idStaff = 0;
					try {
						idStaff = (Integer) target.getModel()
								.getValueAt(row, 0);
						staffFrame(idStaff);
					} catch (Exception ex) {
					}
				}
			}

		});

		return gridStaff;
	}

	private JPanel makeAddStaffPanel() {
		JPanel addPanel = new JPanel();
		GridLayout grid = new GridLayout(0, 2);
		grid.setVgap(4);

		addPanel.setLayout(grid);

		String[] addStaffFields = { "Name", "Address", "Postal Code",
				"Phone No.", "Email", "User Name", "Password" };
		final JTextField[] addStaffTextFields = new JTextField[8];

		for (int i = 0; i < addStaffFields.length; i++) {
			JLabel fieldL = new JLabel(addStaffFields[i]);
			addStaffTextFields[i] = new JTextField(15);

			addPanel.add(fieldL);
			addPanel.add(addStaffTextFields[i]);
		}

		JPanel errMess = new JPanel();
		final JLabel errors = new JLabel();
		errors.setForeground(Color.red);
		errMess.add(errors);

		JPanel addStaffMain = new JPanel();
		addStaffMain.setLayout(new BoxLayout(addStaffMain,
				BoxLayout.Y_AXIS));
		int sp = 8;
		addStaffMain.setBorder(BorderFactory.createCompoundBorder(
				BorderFactory.createTitledBorder(
						BorderFactory.createLineBorder(Color.black),
						"Add Employee"), BorderFactory.createEmptyBorder(sp,
						sp, sp, sp)));

		addStaffMain.add(addPanel);
		addStaffMain.add(errMess);

		JButton addCustButton = new JButton("Add Employee");
		addCustButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				String error = "";

				String name = addStaffTextFields[0].getText();
				String address = addStaffTextFields[1].getText();
				String postalCode = addStaffTextFields[2].getText();
				String phone = addStaffTextFields[3].getText();
				String email = addStaffTextFields[4].getText();
				String user_name = addStaffTextFields[5].getText();
				String password = addStaffTextFields[6].getText();

				if (name.isEmpty())
					error = "The Name field is empty";
				else if (address.isEmpty())
					error = "The Address field is empty";
				else if (postalCode.isEmpty())
					error = "The Postal Code field is empty";
				else if (phone.isEmpty())
					error = "The Phone no. field is empty";
				else if (email.isEmpty())
					error = "The Email field is empty";
				else if (user_name.isEmpty())
					error = "The User name field is empty";
				else if (password.isEmpty())
					error = "The password field is empty";

				if (error != "") {
					errors.setText(error);
				} else {
					errors.setText("");
					staffCtr.createEmployee(idS, name, address, postalCode, phone, email, user_name, password);
					idS++;
					reAddGrid();
				}
			}

		});

		addPanel.add(new JLabel());
		addPanel.add(addCustButton);

		return addStaffMain;
	}

	private void staffFrame(int idS) {

		final JFrame frame = new JFrame("Staff Id: " + idS);
		JPanel mainPanel = new JPanel();

		try {
			final Staff staff = staffCtr.getStaffById(idS);
			JLabel labID = new JLabel("Id");
			JLabel labName = new JLabel("Name");
			JLabel labAddress = new JLabel("Address");
			JLabel labPostalCode = new JLabel("Postal Code");
			JLabel labPhone = new JLabel("Phone Number");
			JLabel labEmail = new JLabel("Email");
			JLabel labUName = new JLabel("User name");
			JLabel labPWord = new JLabel("Password");

			int cols = 7;
			JLabel llab1 = new JLabel();

			final JTextField textID = new JTextField(cols);
			final JTextField textName = new JTextField(cols);
			final JTextField textAddress = new JTextField(cols);
			final JTextField textPostalCode = new JTextField(cols);
			final JTextField textPhone = new JTextField(cols);
			final JTextField textEmail = new JTextField(cols);
			final JTextField textUName = new JTextField(cols);
			final JTextField textPWord = new JTextField(cols);

			textID.setText(String.valueOf(staff.getId()));
			textName.setText(staff.getName());
			textAddress.setText(staff.getAddress());
			textPostalCode.setText(staff.getPostCode());
			textPhone.setText(staff.getPhone());
			textEmail.setText(staff.getEmail());
			textUName.setText(staff.getUsername());
			textPWord.setText(staff.getPassword());

			JPanel grid1 = new JPanel();
			JPanel grid2 = new JPanel();
			JPanel grid3 = new JPanel();

			GridLayout gridLay = new GridLayout(0, 2);
			GridLayout gridLay3 = new GridLayout(0, 2);

			gridLay3.setHgap(20);

			grid1.setLayout(gridLay);
			grid2.setLayout(gridLay);
			grid3.setLayout(gridLay3);

			grid1.add(labID);
			grid1.add(textID);

			grid1.add(labName);
			grid1.add(textName);

			grid1.add(labAddress);
			grid1.add(textAddress);

			grid1.add(labPostalCode);
			grid1.add(textPostalCode);

			grid2.add(labPhone);
			grid2.add(textPhone);

			grid2.add(labEmail);
			grid2.add(textEmail);

			grid2.add(labUName);
			grid2.add(textUName);

			grid2.add(labPWord);
			grid2.add(textPWord);

			grid3.add(grid1);
			grid3.add(grid2);

			JPanel buttonPanel = new JPanel();
			JButton addButton = new JButton("Save");
			JButton deleteButton = new JButton("Delete");
			final JButton cancelButton = new JButton("Cancel");

			buttonPanel.add(addButton);
			buttonPanel.add(deleteButton);
			buttonPanel.add(cancelButton);
			
			deleteButton.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent e) {
					if(!staff.getUsername().equals(Main.logUS)) {
						staffCtr.deleteStaff(staff.getId());
						cancelButton.doClick();
						reAddGrid();
					}
				}
			});
			
			
			cancelButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent ev) {
					frame.setVisible(false);

				}
			});

			addButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {

					String name = textName.getText();
					String address = textAddress.getText();
					String postalCode = textPostalCode.getText();
					String phone = textPhone.getText();
					String email = textEmail.getText();
					String user_name = textUName.getText();
					String password = textPWord.getText();

					// try {}
					// catch (ParseException pe) {}

					if (name.isEmpty())
						popupError("Name field is empty");
					else if (address.isEmpty())
						popupError("Address field is empty");
					else if (postalCode.isEmpty())
						popupError("Postal Code field is empty");
					else if (phone.isEmpty())
						popupError("Phone number field is empty");
					else if (email.isEmpty())
						popupError("Email field is empty");
					else if (user_name.isEmpty())
						popupError("User name field is empty");
					else if (password.isEmpty())
						popupError("Password field is empty");
					else {
						int answer = JOptionPane.showConfirmDialog(frame,
								"Do you wish to save? ", "Confirm saving",
								JOptionPane.YES_NO_OPTION);

						if (answer == JOptionPane.YES_OPTION) {
							staff.setName(name);
							staff.setAddress(address);
							staff.setPostCode(postalCode);
							staff.setPhone(phone);
							staff.setEmail(email);
							staff.setUsername(user_name);
							staff.setPassword(password);

							frame.setVisible(false);
							reAddGrid();

						}
					}
				}
			});
			mainPanel.add(grid3);
			mainPanel.add(buttonPanel);

		} catch (Exception e) {

		}

		frame.setContentPane(mainPanel);
		frame.setSize(new Dimension(400, 300));
		frame.setResizable(false);
		frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		frame.setVisible(true);
	}

	private void reAddGrid() {
		try {
			panel.remove(1);
			panel.add(makeGridListStaff());
			panel.revalidate();
		} catch (Exception ex) {
		}
	}

	private void popupError(String message) {
		JOptionPane.showMessageDialog(null, message, "Error",
				JOptionPane.INFORMATION_MESSAGE);
	}

	private JPanel makeSearchPanel() {
		JPanel panel = new JPanel();
		int sp = 8;
		panel.setBorder(BorderFactory.createCompoundBorder(
				BorderFactory.createTitledBorder(
						BorderFactory.createLineBorder(Color.black), "Search"),
				BorderFactory.createEmptyBorder(sp, sp, sp, sp)));

		JLabel labSearch = new JLabel("ID or Name ");
		final JTextField textSearch = new JTextField(10);
		JButton searchButton = new JButton("Search");

		searchButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ev) {

				try {
					String search = textSearch.getText();

					int rowHigh = -1;
					for (int i = 0; i < size; i++)
						if (data[i][0].toString().equals(search)
								|| (data[i][1]).toString().equals(search)) {
							rowHigh = i;
							break;
						}

					if (rowHigh >= 0) {
						staffTable.setRowSelectionInterval(rowHigh, rowHigh);
						staffTable.scrollRectToVisible(staffTable.getCellRect(
								rowHigh, 0, true));
					}
				} catch (Exception ex) {
				}
			}

		});

		panel.add(labSearch);
		panel.add(textSearch);
		panel.add(searchButton);

		return panel;
	}

	public JPanel makeStaffTab() {
		panel = new JPanel();
		JPanel fourthPanel = new JPanel();
		fourthPanel.add(makeSearchPanel());
		fourthPanel.add(makeAddStaffPanel());

		panel.add(fourthPanel);
		panel.add(makeGridListStaff());

		return panel;
	}

	private int getSelectedStaff(JTable table) {
		int count = 0;
		for (int i = 0; i < table.getRowCount(); i++) {
			if ((Boolean) table.getValueAt(i, 8) == true)
				count++;
		}
		return count;
	}

	private void deleteSelectedStaff(JTable table) {
		for (int i = 0; i < table.getRowCount(); i++) {
			if ((Boolean) table.getValueAt(i, 8) == true) {
				int staffId = (Integer) table.getValueAt(i, 0);
				staffCtr.deleteStaff(staffId);
			}
		}
		reAddGrid();
	}

}